import React, { Fragment } from 'react'
import { Checkbox, Modal } from 'antd-mobile'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { actionAdd, actionDel, actionInitCartList, actionChangePrice } from '@/store/cart/actions'
import './index.scss'

const alert = Modal.alert

class Cart extends React.Component {
  state = {
    topChecked: true, // 头部按钮的选中情况
    // 商品 goods_id 的集合
    goodsChecked: (this.props.cartList.length > 0) ? this.props.cartList.map(item => item.goods_id) : [], 
    flag: true // 底部的总价以及确认按钮的样式控制开关
  }

  render() {
    const { cartList, cartFlag, storeName, totalPrice } = this.props
    let newTotalPrice = totalPrice
    let allTotalPrice = []

    return (
      <Fragment>
        <div className='cart'>
          {/* 购物车头部 */}
          <div className='cart_header'>
            <div className='cart_header_left'>
              <i
                className='iconfont iconarrow-down'
                onClick={() => {
                  this.props.history.goBack()
                }}
              />
            </div>

            <div className='cart_header_title'>
              <h1>购物车</h1>
            </div>

            <div className='cart_header_right'>
              <i className='iconfont iconshenglvehao' />
            </div>
          </div>

          {/* 购物车商品信息 */}
          <div className='cart_content' style={{ display: cartFlag === true ? 'block' : 'none' }}>
            <div className='cart_store'>
              <div className='top_check'>
                <Checkbox
                  checked={this.state.topChecked}
                  onChange={e => {
                    // 将 cartList 所有的商品id 都抽出来，组成一个新数组
                    let goodsChecked = cartList.map(item => item.goods_id)

                    allTotalPrice = cartList.map(item => ((item.goods_num * (item.goods_price * 100)) / 100))
                    allTotalPrice = (allTotalPrice.reduce((prev, cur) => prev + cur)).toFixed(2)

                    /* 顶部控制按钮选中，将新数组赋值给 goodsChecked ，否则清空 goodsChecked */
                    if (e.target.checked) {
                      this.props.handleChangePrice(allTotalPrice)

                      this.setState({
                        goodsChecked
                      })
                    } else {
                      this.props.handleChangePrice(0)
                      this.setState({
                        goodsChecked: []
                      })
                    }

                    this.setState({
                      topChecked: e.target.checked,
                      flag: !this.state.topChecked
                    })
                  }}
                />
              </div>
              <i className='iconfont icondianpu'/>
              <span>{storeName}</span>
            </div>
            <ul>
              {
                cartList.map(item => {

                  return (
                    <li key={item.goods_id}>
                      <div className='cart_goods_check'>
                        <Checkbox
                          checked={this.state.goodsChecked.includes(item.goods_id)}
                          onChange={() => {
                            let goodsChecked = [...this.state.goodsChecked];

                            let index = goodsChecked.findIndex(a => a === item.goods_id)

                            /* 判断目标按钮对应的 goods_id 是否存在 goodsChecked 数组中，如果存在，将它移出数组，否则添加进数组 */
                            if (index >= 0) {
                              goodsChecked.splice(index, 1);

                              newTotalPrice = ((newTotalPrice * 100 - 100 * (item.goods_num * item.goods_price)) / 100).toFixed(2)
                              this.props.handleChangePrice(newTotalPrice)

                              this.setState({
                                goodsChecked
                              })
                            } else {
                              goodsChecked.push(item.goods_id);

                              newTotalPrice = ((newTotalPrice * 100 + 100 * (item.goods_num * item.goods_price)) / 100).toFixed(2)
                              this.props.handleChangePrice(newTotalPrice)

                              this.setState({
                                goodsChecked
                              })
                            }

                            // 根据 goodsChecked 的长度为零时，底部控制开关应为 false
                            if (goodsChecked.length > 0) {
                              this.setState({
                                flag: true
                              })
                            } else {
                              this.setState({
                                flag: false
                              })
                            }
                          }}
                        />
                      </div>
                      <div className='cart_goods_pic'>
                        <img src={item.goods_image_url} alt="" />
                      </div>
                      <div className='cart_goods_info'>
                        <p className='cart_goods_info_name'>{item.goods_name}</p>
                        
                        <div style={{ width: '100px' }}>&nbsp;</div>
                        
                        <span className='cart_goods_info_price'>￥{item.goods_price}</span>
                        
                        <i className='iconfont iconshanchu'
                          onClick={() => {
                            alert('', '确定删除吗？', [
                              {
                                text: '确定',
                                onPress: () => {
                                  this.props.handleDel(item.id, this.props)
                                }
                              },
                              {
                                text: '取消',
                                onPress: () => {}
                              }
                            ])
                          }}
                        />

                        {/* 商品数量加减 */}
                        <div className='goods_count'>
                          <span
                            className='goods_reduce'
                            onClick={() => {
                              let btnType = 'reduce'
                              if (item.goods_num > 1) {
                                this.props.handleAdd(item, btnType)
                              }
                            }}
                          >-</span>
                          <span className='goods_number'>{item.goods_num}</span>
                          <span
                            className='goods_add'
                            onClick={() => {
                              let btnType = 'add'
                              this.props.handleAdd(item, btnType)
                            }}
                          >+</span>
                        </div>
                        
                        {/* 当前面的按钮的 checked 为 false 时，遮罩层挡住 goods_count ，不让它点击加减商品 */}
                        <div
                          className='goods_none'
                          style={{ display: this.state.goodsChecked.includes(item.goods_id) ? 'none' : 'block' }}
                        />
                      </div>
                    </li>
                  )
                })
              }
            </ul>
          </div>
          {/* 无商品 */}
          <div className='cart_none' style={{ display: cartFlag === true ? 'none' : 'block'}}>
            <p>购物车为空</p>
            <p>
              <Link to='/home'>随便逛逛</Link>
            </p>
            
          </div>

          {/* 购物车底部 */}
          <div
            className='cart_footer'
            style={{ display: cartFlag === true ? 'flex' : 'none' }}
          >
            <div className='all_checked'>
              <Checkbox
                defaultChecked
                onChange={e => {
                  let list = cartList.map(item => item.goods_id)
                  let goodsChecked = [...list]

                  allTotalPrice = cartList.map(item => ((item.goods_num * (item.goods_price * 100)) / 100))
                  allTotalPrice = (allTotalPrice.reduce((prev, cur) => prev + cur)).toFixed(2)

                  if (e.target.checked) {
                    this.props.handleChangePrice(allTotalPrice)

                    this.setState({
                      goodsChecked
                    })
                  } else {
                    this.props.handleChangePrice(0)
                    this.setState({
                      goodsChecked: []
                    })
                  }
                  
                  this.setState({
                    topChecked: e.target.checked,
                    flag: e.target.checked
                  })
                }}
              />
            </div>

            <div className='cart_footer_total'>
              <span className='cart_footer_total_price'>
                ￥{ this.state.flag ? totalPrice : '0.00'}
              </span>
              <span>合计总金额：</span>
            </div>

            <div
              className='cart_footer_ok'
              style={{ background: this.state.flag ? '#ED5564' : '#bbb'}}
              >
              {
                this.state.flag ? <Link to='/special'>确认信息</Link> : '确认信息'
              }
            </div>
          </div>
        </div>
      </Fragment>
    )
  }

  componentDidMount() {
    this.props.handleInitCartList(this.props)
  }
}

export default connect(
  state => ({
    cartList: state.cart.cartList, // 购物车商品列表
    totalPrice: state.cart.totalPrice, // 购物车商品总价格
    storeName: state.cart.storeName, // 最后添加进购物车的商品 店铺名字
    cartFlag: state.cart.cartFlag // 购物车商品数量控制器
  }),
  dispatch => ({
    /* 初始化购车车页面 */
    handleInitCartList(props) {
      dispatch(actionInitCartList(props))
    },

    /* 根据点击按钮的 btnType，增减商品的数量 */
    handleAdd(goodsInfo, btnType) {
      goodsInfo = JSON.parse(JSON.stringify(goodsInfo))
      dispatch(actionAdd(goodsInfo, btnType))
    },

    /* 删除购物车商品 */
    handleDel(id, props) {
      dispatch(actionDel(id, props))
    },

    /* 点击页面的按钮，修改仓库的商品总价格 */
    handleChangePrice(newTotalPrice) {
      dispatch(actionChangePrice(newTotalPrice))
    }
  })
)(Cart)
